package com.hnja.hcg.netty;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnja.hcg.entity.hcg.TcpBean;
import com.hnja.hcg.entity.sys.YDRackTaskInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Created by Administrator on 2018/4/4 0004.
 */

@ChannelHandler.Sharable
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    private static final String TAG = "NettyClientHandler";
    private StringBuffer mMessageBuffer = new StringBuffer();
    private INettyClient.OnConnectStatusListener statusListener;
    private List<INettyClient.OnDataReceiveListener> listeners = new ArrayList<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Log.e(TAG, "channelActive: ");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        //数据 开始部位 带判断
        Log.e(TAG, "channelRead: " + msg);
        try {
            String body = (String) msg;
            if (body != null) {
                if (body.startsWith("@")) {
                    mMessageBuffer.delete(0, mMessageBuffer.length());
                }
                mMessageBuffer.append(body);
                if (body.endsWith("@")) {
                    String messageBody = mMessageBuffer.toString().replace("@", "");
                    parseJson(messageBody);
                    mMessageBuffer.delete(0, mMessageBuffer.length());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            mMessageBuffer.delete(0, mMessageBuffer.length());
        }
    }

    private String verify(String body) {
        return null;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Log.e(TAG, "exceptionCaught: ");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        Log.e(TAG, "channelReadComplete: ");
    }

    private void parseJson(String message) throws JSONException {

        Gson gson = new Gson();
        TcpBean tcpBean = gson.fromJson(message, TcpBean.class);
        callListeners(tcpBean);
    }

    private void callListeners(TcpBean tcpBean) {
        for (final INettyClient.OnDataReceiveListener listener : listeners)
            if (listener != null)
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {//主线程中进行
                        listener.onDataReceive(tcpBean);
                    }
                });
    }

    public void addDataReceiveListener(INettyClient.OnDataReceiveListener listener) {
        if (!listeners.contains(listener))
            listeners.add(listener);
    }

    public void setConnectStatusListener(INettyClient.OnConnectStatusListener listener) {
        statusListener = listener;
    }


}
